package com.qf.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

@Controller
public class UploadController {


    @PostMapping("/upload")
    public String upload(MultipartFile pic, HttpSession session) throws IOException {
       //校验图片真假
        BufferedImage bufferedImage = ImageIO.read(pic.getInputStream());
        if (bufferedImage==null){
            //假图  计算宽高
            return null;
        }

        //1.获取文件的原名字（拿后缀）
        String originalFilename = pic.getOriginalFilename();
        String suffixName=originalFilename.substring(originalFilename.lastIndexOf("."));
        //2.生成新名称
        String newName= UUID.randomUUID().toString().replace("-","")+suffixName;

        //通过pic保存图片到本地

        String realPath = session.getServletContext().getRealPath("/WEB-INF/upload/");
        File file=new File(realPath);
        if (!file.exists()){
            file.mkdirs();
        }
        pic.transferTo(new File(file+newName));
//        IOUtils.copy(pic.getInputStream(),new FileOutputStream(file1));


//        pic.getInputStream();
        return null;
    }

}
